#!/usr/bin/env python
#coding=utf-8

from logging import getLogger, Formatter, INFO, FATAL
from concurrent_log_handler import ConcurrentRotatingFileHandler
import os

class Logger(object):
    """日志系统
    日志系统继承 logging 与 concurrent_log_handler
    可实现多进程间同时使用同一文件进行日志
    并确保进程间安全

    Attributes:
        file_path: 日志文件名称
        backup_files: 保存几个备份，默认一个
        file_size: 最大文件大小，当大于该大小后，进行文件备份
    """
    def __init__(self, file_path, backup_files = 5, file_size = 512*1024*10):
        ''' 初始化日志系统，文件最大为 512*1024*10=5mb  512*1024*1024=512mb'''
        self._file_path = file_path
        self._backup_files = backup_files
        self._file_size = file_size
        self._logger = getLogger()
        formatter = Formatter('%(asctime)s %(levelname)-4s: %(message)s')
        # Use an absolute path to prevent file rotation trouble.
        logfile = os.path.abspath(self._file_path)
        # Rotate log after reaching 512K, keep 5 old copies.
        rotateHandler = ConcurrentRotatingFileHandler(logfile, "a", self._file_size, self._backup_files)
        rotateHandler.setFormatter(formatter)
        self._logger.addHandler(rotateHandler)
        self._logger.setLevel(INFO)
        
    def debug(self, msg):
        self._logger.debug(msg)
        
    def info(self, msg):
        self._logger.info(msg)
        
    def warn(self, msg):
        self._logger.warn(msg)      
        
    def fatal(self, msg):
        self._logger.fatal(msg)   

    def critical(self, msg):
        self._logger.critical(msg)   
        
    def exception(self, msg):
        self._logger.exception(msg)
        
    def error(self, msg):
        self._logger.error(msg)